package com.estronger.shopmanage.ui.measure.pg;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.estronger.shopmanage.R;
import com.estronger.shopmanage.adapter.tasking.PgMsDetailListAdapter;
import com.estronger.shopmanage.base.BaseActivity;
import com.estronger.shopmanage.base.MyApplication;
import com.estronger.shopmanage.bean.B101PgMeasureList;
import com.estronger.shopmanage.bean.B16PlanMeasure;
import com.estronger.shopmanage.bean.BeanBase;
import com.estronger.shopmanage.bean.ReturnMsgEntity;
import com.estronger.shopmanage.manager.DataManager;
import com.estronger.shopmanage.manager.NetManager;
import com.estronger.shopmanage.utils.DateUtils;
import com.estronger.shopmanage.utils.JsonUtil;
import com.estronger.shopmanage.utils.PermissionUtils;
import com.estronger.shopmanage.utils.PrefUtils;
import com.estronger.shopmanage.view.AppDialog;
import com.estronger.shopmanage.view.CustomListView;
import com.estronger.shopmanage.view.SelectPeopleActivity;
import com.estronger.shopmanage.view.WiperSwitch;
import com.estronger.shopmanage.view.picker.DateTimePicker;
import com.lidroid.xutils.http.RequestParams;

import java.util.Date;
import java.util.HashMap;

import static com.estronger.shopmanage.manager.DataManager.condMap;
import static com.estronger.shopmanage.manager.DataManager.msiteMap;
import static com.estronger.shopmanage.manager.DataManager.selectedCondMap_M;

/**
 * Created by Soonfor on 2017/5/12.
 * 测量条件确认
 */

public class MsAffirmCondActivity extends BaseActivity implements
        View.OnClickListener, WiperSwitch.OnChangedListener {

    private Activity mActivity;
    private View rootView;
    private ScrollView sv_root;
    private B101PgMeasureList.Datas.PgMeasureListData comdata;
    private String measureid;
    private TextView tv_title, tvfName, tvfAddress, tvfSales,
            tvfOrderTimeT, tvfOrderTime, tvfYyTime, tvfDesigner;
    private ImageView ivfCallToCustomer, ivfSendToCustomer, ivfCallToSales, ivfSendToSales;
    private String cstName, cstphoneNumber, salesName, salesphoneNumber;
    private CustomListView goodsListView;
    private WiperSwitch wSwitch;//是否同时派工的开关
    private String ifassigndesigner = "0";
    private LinearLayout llfMsPG, llfDispatching;//同时派工展开,初次沟通
    private EditText etfRemark;//初步沟通输入框
    private RelativeLayout rlfAppointment, rlfDesinger;//选择预约时间、选择设计师
    private FloatingActionButton fab;
    private Dialog dialog;
    private boolean isBackBtn;
    private String Communication = "";//初步沟通的内容
    private String fAppointmentDate = "";//预约时间
    @Override
    protected void init() {
        comdata = (B101PgMeasureList.Datas.PgMeasureListData) getIntent().getSerializableExtra("measureItem");
        if (comdata != null) {
            measureid = comdata.measureid;
            if(selectedCondMap_M !=null &&selectedCondMap_M.size()>0){
                condMap = selectedCondMap_M.get(measureid);
            }
            if(condMap==null){condMap = new HashMap<>();}
        }
    }

    @Override
    public void onBackViewClick(View view) {
        if (isChanged()) {
            dialog = AppDialog.createEjectNoticeDialog(mActivity, this);
            isBackBtn = true;
            dialog.show();
        } else {
            finish();
        }
    }

    @Override
    protected void initView() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        mActivity = MsAffirmCondActivity.this;
        rootView = View.inflate(mActivity, R.layout.activity_pg_ms_affirmcondition, null);
        setContentView(rootView);
        tv_title = (TextView) findViewById(R.id.ab_title);
        tv_title.setText("测量条件确认");
        sv_root = (ScrollView) findViewById(R.id.detail_pgscroller);
        RequestParams params = new RequestParams();
        params.addBodyParameter("sf_action", "getplanmeasure");
        params.addBodyParameter("usercode", MyApplication.getUserCode());
        params.addBodyParameter("measureid", measureid);
        connect(params, NetManager.PG_MS_DETAIL);
        fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(mActivity, MsPGTripActivity.class));
            }
        });
        initTitle(sv_root);
        goodsListView.setFocusable(false);
        setTextContent();
    }

    @Override
    protected void initAction() {
        super.initAction();
        ivfCallToCustomer.setOnClickListener(this);
        ivfCallToSales.setOnClickListener(this);
        ivfSendToCustomer.setOnClickListener(this);
        ivfSendToSales.setOnClickListener(this);
        rlfAppointment.setOnClickListener(this);
        rlfDesinger.setOnClickListener(this);
        wSwitch.setOnChangedListener(this);
        etfRemark.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_MOVE:
                        v.getParent().requestDisallowInterceptTouchEvent(true);
                        break;
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                        v.getParent().requestDisallowInterceptTouchEvent(false);
                        break;
                }
                return false;
            }
        });
        etfRemark.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                Communication = etfRemark.getText().toString();
            }
        });
        llfDispatching.setVisibility(View.GONE);
    }

    private void initTitle(View root) {

        tvfName = (TextView) root.findViewById(R.id.tvfItemTitle);
        tvfAddress = (TextView) root.findViewById(R.id.tvfItemLocation);
        tvfSales = (TextView) root.findViewById(R.id.tvfSales);
        tvfOrderTimeT = (TextView) root.findViewById(R.id.tvfOrderTimeT);
        tvfOrderTime = (TextView) root.findViewById(R.id.tvfOrderTime);

        ivfCallToCustomer = (ImageView) root.findViewById(R.id.ivfMCall);
        ivfCallToSales = (ImageView) root.findViewById(R.id.ivfMCallSales);
        ivfSendToCustomer = (ImageView) root.findViewById(R.id.ivfMSendms);
        ivfSendToSales = (ImageView) root.findViewById(R.id.ivfMSendToSales);

        goodsListView = (CustomListView) root.findViewById(R.id.cLvfGoods);
        wSwitch = (WiperSwitch) root.findViewById(R.id.wsfONOFF);
        llfMsPG = (LinearLayout) root.findViewById(R.id.llfMsPG);
        llfDispatching = (LinearLayout) root.findViewById(R.id.llfDispatching);
        etfRemark = (EditText) root.findViewById(R.id.etfRemark);

        rlfAppointment = (RelativeLayout) root.findViewById(R.id.rlfYyTime);
        rlfDesinger = (RelativeLayout) root.findViewById(R.id.rlfDesigner);
        tvfYyTime = (TextView) root.findViewById(R.id.tvfYyTime);
        tvfDesigner = (TextView) root.findViewById(R.id.tvfDesigner);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivfMSendms:
                if (isRightNumber(cstphoneNumber)) {
                    Uri uri = Uri.parse("smsto:" + cstphoneNumber);
                    Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
                    startActivity(intent);
                }
                break;
            case R.id.ivfMSendToSales:
                if (isRightNumber(salesphoneNumber)) {
                    Uri uri = Uri.parse("smsto:" + salesphoneNumber);
                    Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
                    startActivity(intent);
                }
                break;
            case R.id.ivfMCall:
                if (isRightNumber(cstphoneNumber)) {
                    dialog = AppDialog.createDialog(this, cstName, cstphoneNumber, this, measureid);
                    isBackBtn = false;
                    dialog.show();
                }
                break;
            case R.id.ivfMCallSales:
                if (isRightNumber(salesphoneNumber)) {
                    dialog = AppDialog.createDialog(this, salesName, salesphoneNumber,
                            this, measureid);
                    isBackBtn = false;
                    dialog.show();
                }
                break;
            case R.id.ok:
                if (isBackBtn) {
                    if(selectedCondMap_M ==null || selectedCondMap_M.get(measureid) ==null){
                        condMap.clear();
                        msiteMap.clear();
                    }
                    finish();
                } else {
                    if (PermissionUtils.isCallPhoneGranted(mActivity)) {
                        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"
                                + salesphoneNumber));
                        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                            // TODO: Consider calling
                            //    ActivityCompat#requestPermissions
                            // here to request the missing permissions, and then overriding
                            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                            //                                          int[] grantResults)
                            // to handle the case where the user grants the permission. See the documentation
                            // for ActivityCompat#requestPermissions for more details.
                            return;
                        }
                        startActivity(intent);
                    } else {
                        PermissionUtils.ToSetPermissions(mActivity, R.string.PermissionsCallPhone);
                    }
                }
                dialog.dismiss();
                break;
            case R.id.rlfYyTime:
                DateUtils.onYearMonthDayTimePicker(mActivity, 15, "预约时间", dateTimeListener);
                break;
            case R.id.rlfDesigner:
                SelectPeopleActivity.open(mActivity, 1, measureid, false);
                break;

        }
    }

    /**
     * 当前activity请求网络成功的回调
     *
     * @params code 各个接口返回的唯一识别码，用来判断是哪个接口成功返回
     * @params result 网络请求成功返回的数据
     */
    @Override
    protected void onNetSuccess(int code, String result) {
        super.onNetSuccess(code, result);
        if (NetManager.PG_MS_DETAIL == code) {
            showCompleshView(result);
        }
        if (NetManager.PG_MS_CONDTION_SURE == code) {
            ReturnMsgEntity reEntity = JsonUtil.returnMsgEntity(result);
            if (reEntity.getSuccess() && reEntity.msgcode==0) {
                if(ifassigndesigner.equals("0")){
                    selectedCondMap_M.put(measureid,condMap);
                    AppDialog.showTaskingDialog(mActivity, R.drawable.send_success, "条件确认成功").show();
                }else{
                    AppDialog.showTaskingDialog(mActivity, R.drawable.send_success, "任务派送成功").show();
                    try{
                        selectedCondMap_M.remove(measureid);
                    }catch (Exception e){}
                }
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                    }
                }, 2000);
            } else {
                String msg = reEntity.getMsg();
                if(ifassigndesigner.equals("0")){
                    if(msg.equals("")) msg = "条件确认失败";
                }else{
                    if(msg.equals("")) msg = "任务派送失败";
                }
                AppDialog.showTaskingDialog(mActivity,R.drawable.send_failure,msg).show();
            }
        }
    }

    //本Activity中请求的数据
    public void showCompleshView(String result) {

        B16PlanMeasure detail = gson.fromJson(result, B16PlanMeasure.class);
        B16PlanMeasure.PlanMeasureData pData = detail.data;
        if (pData == null) {
            return;
        }
        salesName = pData.navname;
        tvfSales.setText(salesName);
        salesphoneNumber = pData.navmobile;
        PgMsDetailListAdapter pdAdapter = new PgMsDetailListAdapter(mActivity, pData.measureitem, goodsListView);
        goodsListView.setAdapter(pdAdapter);
    }

    //上一个Activity带入的数据
    private void setTextContent() {
        if (comdata == null) {
            return;
        }
        if (TextUtils.isEmpty(comdata.cstbuildname)) {
            cstName = comdata.cstname;
        } else {
            cstName = comdata.cstbuildname + "-" + comdata.cstname;
        }
        tvfName.setText(cstName);
        tvfAddress.setText(comdata.address);
        tvfOrderTimeT.setText("下单时间:");
        tvfOrderTime.setText(comdata.ordrdate);
        cstphoneNumber = comdata.cstmobile;
    }

    @Override
    public void OnChanged(WiperSwitch wiperSwitch, boolean checkState) {
        if (checkState) {
            llfMsPG.setVisibility(View.VISIBLE);
            llfDispatching.setVisibility(View.VISIBLE);
            ifassigndesigner = "1";
        } else {
            llfMsPG.setVisibility(View.GONE);
            llfDispatching.setVisibility(View.GONE);
            ifassigndesigner = "0";
            fAppointmentDate = "";
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (isChanged()) {
                dialog = AppDialog.createEjectNoticeDialog(mActivity, this);
                isBackBtn = true;
                dialog.show();
            } else {
                finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    //预约时间
    DateTimePicker.OnYearMonthDayTimePickListener dateTimeListener = new DateTimePicker.OnYearMonthDayTimePickListener() {
        @Override
        public void onDateTimePicked(int index, String year) {
            if (index == 0) {
                long nowDate = System.currentTimeMillis();
                Date d = new Date(nowDate);
                String s = year.replace("今天", (DateTimePicker.beforNumDay(d, 0) + DateTimePicker.getWeekOfDate(d, 0 - 1)));
                if (s.length() < 10) {
                    return;
                } else {
                    tvfYyTime.setText(s);
                    fAppointmentDate = DateTimePicker.BackDateToTime(s);
                }
            } else {
                if (year.length() < 10) {
                    return;
                } else {
                    tvfYyTime.setText(year);
                    fAppointmentDate = DateTimePicker.BackDateToTime(year);
                }
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        String name = MyApplication.selectPeople;
        if (name != null) {
            tvfDesigner.setText(name + "");
        }
    }

    /**
     * 保存按钮事件
     * @param view
     */
    public void save(View view) {
        if (ifassigndesigner.equals("1")) {
            if (tvfYyTime.getText().toString() == null || tvfYyTime.getText().toString().equals("")) {
                Toast.makeText(mActivity, "预约测量时间不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            if (tvfDesigner.getText().toString() == null || tvfDesigner.getText().toString().equals("")) {
                Toast.makeText(mActivity, "请选择设计师", Toast.LENGTH_SHORT).show();
                return;
            }
        }

        if (ifassigndesigner.equals("0")) {
            MyApplication.selectID = "";
        }
        DataManager.setNoSelectItem();
        RequestParams params = new RequestParams();
        params.addBodyParameter("sf_action", "confirmcondition");
        params.addBodyParameter("usercode", MyApplication.getUserCode());
        params.addBodyParameter("measureid", measureid);
        params.addBodyParameter("ifassigndesigner", ifassigndesigner);
        params.addBodyParameter("newplanmeasuredate", fAppointmentDate);
        params.addBodyParameter("newplandesignerid", MyApplication.selectID);
        params.addBodyParameter("firstdemand", Communication);
        params.addBodyParameter("measureitem", DataManager.getJsonByMap(msiteMap));
        connect(params, NetManager.PG_MS_CONDTION_SURE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.selectPeople = "请选择";
        MyApplication.selectID = "";
    }

    //界面是否有修改
    private boolean isChanged() {
        if ((msiteMap == null || msiteMap.size() == 0)) {
            if (ifassigndesigner.equals(0)) {
                return false;
            } else if ((tvfYyTime.getText().toString() == null || tvfYyTime.getText().toString().equals("")) &&
                    fAppointmentDate.equals("") &&
                    Communication.equals("")) {
                return false;
            }
        }
        return true;
    }
}
